package com.example.myapplication.service;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;

import com.example.myapplication.WordApp;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

public class MusicController extends Binder {

    private MediaPlayer mPlayer;

    private PlayListener mListener;
    private boolean isInited = false;
    private AtomicBoolean updateProgress = new AtomicBoolean(true);
    private int pos = 0;

    public void updateProgress(boolean what) {
        updateProgress.set(what);
    }

    public MusicController(MediaPlayer player) {
        mPlayer = player;
    }

    private void play() {  //准备 并开始播放

        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if(mPlayer != null && mListener != null && updateProgress.get()) {
                    int duration = mPlayer.getDuration();
                    int curr = mPlayer.getCurrentPosition();
                    mListener.onProgress(curr, duration);
                }
            }
        }, 0  , 5);

        mPlayer.reset();
        String path = WordApp.AppContext
                .getExternalFilesDir("")
                .getAbsolutePath()+"/voice.wav";
        Uri uri = Uri.fromFile(new File(path));
        mPlayer = MediaPlayer.create(WordApp.AppContext, uri);
        mPlayer.seekTo(pos);
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                pos = 0;
                mPlayer.seekTo(pos);
                int duration = mPlayer.getDuration();
                int curr = mPlayer.getCurrentPosition();
                mListener.onProgress(curr, duration);
            }
        });
        mPlayer.start();
        isInited = true;
    }
    public void pause() {  //暂停播放
        mPlayer.pause();
    }
    public void resume() {
        if(isInited) {
            mPlayer.start();//继续播放
        }
        else {
            play();//从头播放
        }
    }
    public void seek(int ms) {
        pos = ms;
        //进度调整
        mPlayer.seekTo(pos);
    }

    public void setPlayListener(PlayListener listener) {
        mListener = listener;
    }
}
